package day17.tarena.GUI;
import java.awt.*;
import java.awt.event.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.*;
public class RegisterCheak implements ActionListener{
	private String result ="";
	private String[] s1;
	private String[] s2;

	JTextField jtf1 = new JTextField(15);
	JTextField jtf2 = new JTextField(15);
	JTextField jtf3 = new JTextField(15);
	JLabel jl1 = new JLabel("欢迎注册");
	
	private boolean state=false;
	class rhc {
		public rhc() throws Exception {
			FileInputStream fis = new FileInputStream(
					"/home/hfsd0909/register.txt");
			byte[] b = new byte[1024];
			while (true) {
				int num = fis.read(b);
				if (num == -1)
					break;
				result = result + new String(b, 0, num);
			}
			fis.close();
				s1 = result.split(";");
				for(int i =0; i<s1.length; i++){
					s2 = s1[i].split("\\,");
					for(int j=0; j<s2.length; j++){
					}	System.out.println(s2[0]);
					if(s2[0].equals(jtf1.getText())){
						state =true;
						break;
					}else{
						state = false;
					}
				}
			}
		}
	public void actionPerformed(ActionEvent ae){
		String comm = ae.getActionCommand();
		if("提交".equals(comm)){
			String name = jtf1.getText();
			String passwd = jtf2.getText();
			String email = jtf3.getText();
			String temp = name+","+passwd+","+email+";";
			try {
				new rhc();
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(state){
				jl1.setText("注册失败!用户名已存在!");
			}else {
				try{
				  FileOutputStream fos = new 
				    FileOutputStream("/home/hfsd0909/register.txt",true);
				  fos.write(temp.getBytes());
				  fos.close();
				  jl1.setText("注册成功");
				}catch(Exception ee){
					ee.printStackTrace();
					jl1.setText("注册失败");
				}
				jtf1.setText("");
				jtf2.setText("");
				jtf3.setText("");
			}
		}else{
			jtf1.setText("");
			jtf2.setText("");
			jtf3.setText("");
			jtf1.requestFocus();//光标回到jtf1
			jl1.setText("欢迎注册");
		}
	}
    public RegisterCheak(){
    	JFrame jf = new JFrame("用户注册");
    	jf.setLayout(new GridLayout(5,1));
    	JPanel[] jp = new JPanel[5];
    	for(int i=0;i<jp.length;i++){
    		jp[i] = new JPanel();
    		jf.add(jp[i]);
    	}
    	jp[0].add(jl1);
    	JLabel jl2 = new JLabel("用户名：");
    	jp[1].add(jl2);
    	jp[1].add(jtf1);
    	JLabel jl3 = new JLabel("  密 码 ：");
    	jp[2].add(jl3);
    	jp[2].add(jtf2);
    	JLabel jl4 = new JLabel("  email ：");
    	jp[3].add(jl4);
    	jp[3].add(jtf3);
    	JButton jb1 = new JButton("提交");
    	JButton jb2 = new JButton("清空");
    	jp[4].add(jb1);
    	jp[4].add(jb2);
    	jb1.addActionListener(this);
    	jb2.addActionListener(this);
		jf.setLocation(300,200);//设置出现位置
		jf.pack();
		jf.setVisible(true);//设置可见
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
	public static void main(String[] args) {
		new RegisterCheak();
	}

}